package com.jinzhi.jzweb.service.impl.moduleConfig;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.domain.moduleConfig.TrackDrawDO;
import com.jinzhi.jzweb.pojo.TrainingAgencyPageVo;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.service.moduleConfig.TrackDrawService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.TrackDrawDao;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * <pre>
 * 赛道抽签表（存储抽签信息）
 * </pre>
 * <small> 2024-02-28 09:32:18 | lance</small>
 */
@Service
public class TrackDrawServiceImpl extends CoreServiceImpl<TrackDrawDao, TrackDrawDO> implements TrackDrawService {

    @Autowired
    private StuSignUpComService stuSignUpComService;

    @Autowired
    private CareStuSignUpComRealityService careStuSignUpComRealityService;

    @Autowired
    private DictService dictService;


    //存储处理完后的学校信息
    private List<StuSignUpComDO> distinctStuSignUpComDOS;


    //查询抽签规则
    public String getRule(){
        Map<String, String> map = new HashMap<>();
        map.put("name", "draw_rule");
        map.put("type", "draw_rule");
        return dictService.selDicBy(map);
    }

    /**
     * 领队抽签 需要分页
     *
     * 对每个院校进行检录号抽签
     *
     *
     * @param trackDrawDTO
     * @return
     */
//    @Override
//    public Result<Page<TrackDrawDO>> trackDrawList(TrackDrawDO trackDrawDTO) {
//        String rule = getRule();
//        //查询总条数
//        LinkedList<String> numList = new LinkedList<>();
//        int i = this.selectCount(new EntityWrapper<TrackDrawDO>());
//        for (int j = 1; j <= i; j++) {
//            numList.add(String.valueOf(j));
//        }
//
//        //把需要固定的检录号先从检录号列表中移除
//        List<TrackDrawDO> trackDrawDOS1 = this.selectList(new EntityWrapper<TrackDrawDO>().isNotNull("place_num"));
//        if(null!=trackDrawDOS1 && !trackDrawDOS1.isEmpty()){
//            for (TrackDrawDO trackDrawDO : trackDrawDOS1) {
//                numList.remove(trackDrawDO.getPlaceNum());
//            }
//        }
//
//        //查询已经抽签的检录号 并且删除已经抽完的检录号
//        List<TrackDrawDO> trackDrawDOS = this.selectList(new EntityWrapper<TrackDrawDO>().isNotNull("record_number"));
//        if(null!=trackDrawDOS && !trackDrawDOS.isEmpty()){
//            for (TrackDrawDO trackDrawDO : trackDrawDOS) {
//                numList.remove(trackDrawDO.getRecordNumber());
//            }
//        }
//
//        //查询当前页参赛选手信息 这里需要重复抽签 则当前页的检录号可以重复抽
//        Page<TrackDrawDO> page = new Page<TrackDrawDO>(trackDrawDTO.getPageNumber(),trackDrawDTO.getPageSize());
//        Wrapper<TrackDrawDO> entityWrapper =new EntityWrapper<TrackDrawDO>();
//        entityWrapper.orderBy(true,"sort");
//        Page<TrackDrawDO> pages = this.selectPage(page, entityWrapper);
//        List<TrackDrawDO> records = pages.getRecords();
//
//        //当前页的检录号重新放到抽签的列表中
//        if(null!=records.get(0).getRecordNumber()){
//            for (TrackDrawDO record : records) {
//                if (record.getPlaceNum()==null){
//                    numList.add(String.valueOf(record.getRecordNumber()));
//                }
//                //numList.add(String.valueOf(record.getRecordNumber()));
//            }
//
//        }
//        //打乱一下存放检录号的列表
//        Random random = new Random();
//        Collections.shuffle(numList,random);
//        for (TrackDrawDO record : records) {
//            if(null!=record.getPlaceNum()){
//                record.setRecordNumber(record.getPlaceNum());
//                //numList.remove(record.getPlaceNum());
//            }else{
//                record.setRecordNumber(numList.getFirst());
//                numList.removeFirst();
//            }
//            //检录号同步到真实的选手管理表
//            //检录号 = 规则 + 序号
//            Integer recordSort = Integer.valueOf(record.getRecordNumber());
//            String recordNumber = rule + record.getRecordNumber();
//            CareStuSignUpComRealityDO careStuSignUpComRealityDO = new CareStuSignUpComRealityDO();
//            careStuSignUpComRealityDO.setRecordNumber(recordNumber);
//            careStuSignUpComRealityDO.setRecordSort(recordSort);
//            careStuSignUpComRealityService.update(careStuSignUpComRealityDO,new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name",record.getUnitName()));
//            //同步到虚拟表
//            StuSignUpComDO stuSignUpComDO = new StuSignUpComDO();
//            stuSignUpComDO.setRecordNumber(record.getRecordNumber());
//            stuSignUpComDO.setRecordSort(recordSort);
//            stuSignUpComService.update(stuSignUpComDO,new EntityWrapper<StuSignUpComDO>().eq("unit_name",record.getUnitName()));
//
//        }
//        this.updateBatchById(records);
//        records.get(0).setHasDraw(true);
//        records.get(0).setTotal(pages.getTotal());
//        pages.setRecords(records);
//        return Result.ok(pages);
//    }

    /**
     * 抽签接口
     * @param trackDrawDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<List<TrackDrawDO>> trackDrawList(TrackDrawDO trackDrawDTO) {
        //获取检录号规则
        String rule = getRule();
        Random random = new Random();
        //获取抽签列表
        LinkedList<String> numList = new LinkedList<>();
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
        wrapper.orderBy(true,"sort");
        List<TrackDrawDO> trackDrawDOS = this.selectList(wrapper);
        for (int i = 1; i <= trackDrawDOS.size(); i++) {
            numList.add(String.valueOf(i));
        }
        trackDrawDOS.forEach(trackDrawDO -> {
            if (StringUtils.isNotEmpty(trackDrawDO.getPlaceNum())){
                numList.remove(trackDrawDO.getPlaceNum()) ;
            }
        });

        //打乱一下存放检录号的列表
        Collections.shuffle(numList,random);

        List<CareStuSignUpComRealityDO> realityDOList = new ArrayList<>();
        List<StuSignUpComDO> signUpComDOList = new ArrayList<>();
        for (TrackDrawDO record : trackDrawDOS) {
            String recordNumber = "";
            Integer recordNumberSort=null;
            //判断检录序号是否需要固定
            if(null!=record.getPlaceNum()){
                recordNumberSort= Integer.valueOf(record.getPlaceNum());
                recordNumber=rule+record.getPlaceNum();
                record.setRecordNumberSort(Integer.parseInt(record.getPlaceNum()));
                numList.remove(record.getPlaceNum());
            }else{
                recordNumberSort= Integer.valueOf(numList.getFirst());
                recordNumber=rule+numList.getFirst();
                record.setRecordNumberSort(Integer.parseInt(numList.getFirst()));
                numList.removeFirst();
            }
            //检录号同步到真实的选手管理表
            //检录号 = 规则 + 序号
            CareStuSignUpComRealityDO careStuSignUpComRealityDO = new CareStuSignUpComRealityDO();
            careStuSignUpComRealityDO.setRecordNumber(recordNumber);
            careStuSignUpComRealityDO.setRecordSort(recordNumberSort);
            careStuSignUpComRealityDO.setUnitName(record.getUnitName());
            realityDOList.add(careStuSignUpComRealityDO);
//            //同步到虚拟表
            StuSignUpComDO stuSignUpComDO = new StuSignUpComDO();
            stuSignUpComDO.setRecordNumber(recordNumber);
            stuSignUpComDO.setRecordSort(recordNumberSort);
            stuSignUpComDO.setUnitName(record.getUnitName());
            signUpComDOList.add(stuSignUpComDO);

            record.setRecordNumber(recordNumber);

        }
        if(null!=trackDrawDOS && !trackDrawDOS.isEmpty()){
            this.updateBatchById(trackDrawDOS);
        }
        if(null!=realityDOList && !realityDOList.isEmpty()){
            careStuSignUpComRealityService.updateRecordNumber(realityDOList);
        }
        if(null!=signUpComDOList && !signUpComDOList.isEmpty()){
            stuSignUpComService.updateRecordNumber(signUpComDOList);
        }

        return Result.ok(setTemplate(trackDrawDOS));

    }

    /**
     * 查询上一次的抽签结果
     * @param trackDrawDTO
     * @return
     */
    @Override
    @Transactional
    public List<TrackDrawDO> trackList(TrackDrawDO trackDrawDTO) {
        //存储抽签你信息
        boolean hasDraw = true;//默认为true.不存在上次抽签结果时改为false

        //查询上一次的抽签结果
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
        wrapper.orderBy(true,"sort");
        List<TrackDrawDO> trackDrawDOS = this.selectList(wrapper);

        //如果没有抽签上一次抽签结果那就默认初始化
        if(trackDrawDOS==null || trackDrawDOS.size()==0){
            trackDrawDOS = new ArrayList<>();
            hasDraw = false;
            Wrapper<CareStuSignUpComRealityDO> entityWrapper =new EntityWrapper<>();
            List<CareStuSignUpComRealityDO> stuSignUpComDOS = careStuSignUpComRealityService.selectList(entityWrapper);
            List<CareStuSignUpComRealityDO> distinctStuSignUpComDOS = stuSignUpComDOS.stream()
                    .collect(Collectors.toMap(CareStuSignUpComRealityDO::getUnitName, s -> s, (s1, s2) -> {
                        // 如果placeNum不为空，优先保留具有非空placeNum的对象
                        if (s1.getPlaceNum() != null && !s1.getPlaceNum().isEmpty()) {
                            return s1;
                        } else {
                            return s2;
                        }
                    }))
                    .values()
                    .stream()
                    .sorted(Comparator.comparing(CareStuSignUpComRealityDO::getPlaceNum, Comparator.nullsLast(Comparator.naturalOrder())))
                    .collect(Collectors.toList());
            int i=0;
            for (CareStuSignUpComRealityDO stuSignUpComDO : distinctStuSignUpComDOS) {
                TrackDrawDO trackDrawDO = new TrackDrawDO();
                BeanUtils.copyProperties(stuSignUpComDO,trackDrawDO);
                trackDrawDO.setSort(i+=1);
                trackDrawDO.setRecordNumber(null);
                trackDrawDOS.add(trackDrawDO);
            }
            this.insertBatch(trackDrawDOS);
        }else {
            if (trackDrawDOS.get(0).getRecordNumber()==null) {
                hasDraw = false;
            }
        }
        int size = trackDrawDOS.size();
        List<TrackDrawDO> trackDrawDOS1 = setTemplate(trackDrawDOS);
        trackDrawDOS1.get(0).setHasDraw(hasDraw);
        trackDrawDOS1.get(0).setTotal(size);
        return trackDrawDOS1;
    }

    /**
     * 处理抽签结果数据，改成4*18格式
     */
    public List<TrackDrawDO> setTemplate(List<TrackDrawDO> trackDrawDOS){
        List<TrackDrawDO> trackDrawDOSCopy = new ArrayList<>();//存储最终的抽签结果

        //存储每一行的抽签结果
        TrackDrawDO trackDrawDO1 = new TrackDrawDO();
        List<TrackDrawDO> trackDrawDOSO1 = new ArrayList<>();
        for (int i = 0; i < trackDrawDOS.size(); i++) {
            trackDrawDOSO1.add(trackDrawDOS.get(i));
            if((i+1) % 4 == 0){
                trackDrawDO1.setTrackDrawDOList(trackDrawDOSO1);
                trackDrawDOSCopy.add(trackDrawDO1);
                //清空
                trackDrawDO1 = new TrackDrawDO();
                trackDrawDOSO1 = new ArrayList<>();
            } else if (trackDrawDOS.size()-(i+1)==0) {
                trackDrawDO1.setTrackDrawDOList(trackDrawDOSO1);
                trackDrawDOSCopy.add(trackDrawDO1);
            }
        }
        return trackDrawDOSCopy;
    }

}


